package com.sunlands.deskmate.web;


import com.sunlands.deskmate.client.UserCenterService;
import com.sunlands.deskmate.vo.UsersVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * <p></p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author zl
 * @version 1.0
 * @date Created in 2018/4/15 14:42
 * @copyright: Copyright (c) founders
 */

public class BaseController {

    /**
     * 没有用户登录的情况下，security会返回anonymousUser
     */
    public static final String ANONYMOUS_USER = "anonymousUser";

    /**
     * 该方法不需要访问其他服务，可以在security中获取到用户的用户名和id
     *
     * @return UserInfoDTO
     */
    protected Long currentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object object = authentication.getPrincipal();

        if (object instanceof String) {
            if (ANONYMOUS_USER.equals(object)) {
                return null;
            }
            String[] strings = ((String) object).split("-");
            if (strings.length == 2) {
                return Long.parseLong(strings[1]);
            } else {
                throw new AuthorizationServiceException("client token无法获取到用户信息！");
            }
        } else {
            try {
                throw new AuthorizationServiceException("没有获取到用户线信息！");
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 该方法会调用微服务tz-user-center来获取用户基本信息
     *
     * @return UserInfoDTO
     */
    protected UsersVO currentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object object = authentication.getPrincipal();
        if (object instanceof String) {
            String[] strings = ((String) object).split("-");
            if (strings.length == 2) {
                UsersVO userInfoDTO = userCenterService.getUserInfoById(Long.parseLong(strings[1])).getData();
                return userInfoDTO;
            } else {
                throw new AuthorizationServiceException("client token无法获取到用户信息！");
            }
        } else {
            try {
                throw new AuthorizationServiceException("没有获取到用户线信息！");
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Autowired
    private UserCenterService userCenterService;


}
